package com.ssyc.common.base;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.support.multidex.MultiDex;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.ssyc.common.R;
import com.ssyc.common.map.LocationManager;
import com.ssyc.common.map.LocationResultEntity;
import com.ssyc.common.map.LocationResultListener;
import com.ssyc.common.utils.SPUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.cookie.CookieJarImpl;
import com.zhy.http.okhttp.cookie.store.PersistentCookieStore;
import com.zhy.http.okhttp.https.HttpsUtils;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.OkHttpClient;

/**
 * Created by Administrator on 2018/3/14 0014.
 */

public class BaseApplication extends Application {

    //定义全局的网络请求的返回状态
    public static String ERROR = "服务器异常";

    //定义全局的Context对象
    public static Context context;

    //定义全局的Handler对象
    public static Handler handler;

    //定义主线程对象
    public static Thread mainThread;

    //定义主线程的线程ID
    public static int mainThreadId;

    //设备信息
    //系统信息
    public static String SY_SY = "android";
    //设备ID
//    public static String sy_di;

    //客户端版本
    public static String sy_cv;


    //返回AppLicatinon单例的方法
    private static volatile BaseApplication application;


    /**
     * static 代码段可以防止内存泄露
     * 配置下拉刷新的加载更多的样式
     */

    static {
        //设置全局的Header构建器
//        SmartRefreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
//            @Override
//            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
//                layout.setPrimaryColorsId(R.color.transparent, R.color.srfcolor);//全局设置主题颜色
//                return new ClassicsHeader(context).setSpinnerStyle(SpinnerStyle.Translate);//指定为经典Header，默认是 贝塞尔雷达Header
//            }
//        });
        SmartRefreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.transparent, R.color.white);//全局设置主题颜色
                return new ClassicsHeader(context).setSpinnerStyle(SpinnerStyle.Translate);//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
//                layout.setPrimaryColorsId(R.color.white, android.R.color.darker_gray);
                return new ClassicsFooter(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });
    }


    public static BaseApplication getInstance() {
        if (application == null) {
            synchronized (BaseApplication.class) {
                if (application == null) {
                    application = new BaseApplication();
                }
            }
        }
        return application;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        //解决65536的报错,分包处理
        MultiDex.install(this);

        //初始化上下文等对象
        initConnmon();

        //获取设备信息
        initSystemMsg();

        //初始化okHttpUtils
        initOKhttp();

        //初始化异常处理类,上线后打开这个方法
//        initCrashHandler();

        //配置本地数据库的操作
//        setupDatabase();

        //初始化定位
        initLocation();
    }


    /**
     * 设置本地数据库
     */
    private void setupDatabase() {
        //创建shop.db数据库
//        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "shop.db", null);
        //获取可写数据库
//        SQLiteDatabase db = helper.getWritableDatabase();
        //获取数据库对象
//        DaoMaster daoMaster = new DaoMaster(db);
        //获取Dao对象管理者
//        daoSession = daoMaster.newSession();

    }
//    public static DaoSession getDaoInstant() {
//        return daoSession;
//    }

    /**
     * 初始化OkHttpUtils
     */
    private void initOKhttp() {
        //配置支持Https请求
        //配置Https证书
        try {
            //支持指定证书认证的Https请求
//            HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(new InputStream[
//                    ]{getAssets().open("https.cer")}, null, null);
            //支持所有的Https请求
            HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
            CookieJarImpl cookieJar = new CookieJarImpl(new PersistentCookieStore(getApplicationContext()));
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(new LoggerInterceptor("TAG"))
                    .connectTimeout(5000L, TimeUnit.MILLISECONDS)
                    .readTimeout(5000L, TimeUnit.MILLISECONDS)
                    .cookieJar(cookieJar)
                    .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                    //其他配置
                    .hostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    })
                    .build();
            OkHttpUtils.initClient(okHttpClient);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 初始化异常处理
     */
    private void initCrashHandler() {
        CrashHandler.getInstance().init();
    }


    /**
     * 初始化定位,根据项目需求实现
     */
    private void initLocation() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //启动定位功能呢
                LocationManager.getInstance().start(context);
                LocationManager.getInstance().setLocationResultListener(new LocationResultListener() {
                    @Override
                    public void locationListener(LocationResultEntity entity) {
                        //将当前定位的地址值存入到Sp中, 这里取 区(district)+街道(street)+标志物(aoiName)
//                        SPUtil.put(context, SpKeys.PROVINCE, entity.province);
//                        SPUtil.put(context, SpKeys.CITY, entity.cityName.substring(0, entity.cityName.length() - 1));
//                        SPUtil.put(context, SpKeys.ADDRESS, entity.district + entity.road + entity.aoiName);
//                        SPUtil.put(context, SpKeys.POSTION, entity.aoiName);
//                        SPUtil.put(context, SpKeys.AREA, entity.district + entity.road);

                        //保存省市区
                        SPUtil.put(context, SpKeys.PROVINCE, entity.province);
                        SPUtil.put(context, SpKeys.CITY, entity.cityName);
                        SPUtil.put(context, SpKeys.AREA, entity.district);
                    }
                });
            }
        }).start();
    }


    /**
     * 获取设备信息的方法
     */
    @SuppressLint("MissingPermission")
    private void initSystemMsg() {
        //获取设备版版本号
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        sy_cv = String.valueOf(currentapiVersion);
        //获取设备ID
        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
//        sy_di = tm.getDeviceId();
    }

    /**
     * 初始化一些常用的对象
     */
    private void initConnmon() {
        context = getApplicationContext();
        handler = new Handler();
        mainThread = Thread.currentThread();
        mainThreadId = android.os.Process.myTid();
    }


    /**
     * 判断当前进程是不是UI进程的方法
     *
     * @param context
     * @return
     */
    public static boolean inMainProcess(Context context) {
        String packageName = context.getPackageName();
        String processName = getProcessName(context);
        return packageName.equals(processName);
    }


    /**
     * 获取当前进程名
     *
     * @param context
     * @return 进程名
     */
    public static String getProcessName(Context context) {
        String processName = null;

        // ActivityManager
        ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));

        while (true) {
            for (ActivityManager.RunningAppProcessInfo info : am.getRunningAppProcesses()) {
                if (info.pid == android.os.Process.myPid()) {
                    processName = info.processName;
                    break;
                }
            }

            // go home
            if (!TextUtils.isEmpty(processName)) {
                return processName;
            }

            // take a rest and again
            try {
                Thread.sleep(100L);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
}
